package com.cskaoyan.controller.admin;

import com.cskaoyan.bean.pojo.MallStorage;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author: harveyliu
 * @description: 用来处理文件上传
 * @time: 2021/7/9 10:28
 */
@Controller
public class FileUploadController {

    @Autowired
    FileUploadService fileUploadService;

    @ResponseBody
    @RequestMapping("/admin/storage/create")
    public BaseRespVo uploadImage(MultipartFile file) {
        if (file.isEmpty()) {
            System.out.println("文件为空空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://spring//"; // 上传后的路径
        String newFileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + newFileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        MallStorage mallStorage = new MallStorage(null, newFileName, fileName, file.getContentType(), (int) file.getSize(), "http://localhost:8083/wx/storage/fetch/" + newFileName, new Date(), new Date(), null);

        fileUploadService.uploadImage(mallStorage);

        return BaseRespVo.ok(mallStorage);
    }




}
